package com.example.fisttestproject;

import android.content.Context;
import android.util.Log;

import com.example.fisttestproject.database.AppDatabase;
import com.example.fisttestproject.util.Const;
import com.example.fisttestproject.util.Util;
import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;

import java.util.concurrent.TimeUnit;

public class AndServiceInit {
    private static final String TAG = "AndServiceInit";
    public volatile static    Server INSTANCE;

    public static void start(Context context) {
        if (context == null){
            Log.e(TAG,String.format("context 不能为null"));
            return;
        }
        if (INSTANCE != null ){
            Log.i(TAG, String.format("是否启动成功%s", INSTANCE.isRunning()));
        }
        if (INSTANCE == null) {
            synchronized (AndServiceInit.class) {
                if (INSTANCE == null) {
                    System.out.println("getIp"+ Util.getLocalIPAddress());
                    INSTANCE = AndServer.webServer(context)
                            .port(Const.GLOBAL.SERVER_PORT)
//                    .inetAddress((Util.getLocalIPAddress()))//获取手机的IP地址
                            .timeout(10, TimeUnit.SECONDS)
                            .listener(new Server.ServerListener() {
                                @Override
                                public void onStarted() {
                                    // TODO The server started successfully.
                                    Log.e(TAG, "onStarted: "+"服务器启动 Ip:"+ Util.getLocalIPAddress());
                                }

                                @Override
                                public void onStopped() {
                                    // TODO The server has stopped.
                                    Log.e(TAG, "onStarted: "+"服务器停止");
                                }

                                @Override
                                public void onException(Exception e) {
                                    // TODO An exception occurred while the server was starting.
                                    Log.e(TAG, "onStarted: "+"服务器异常"+e.getMessage());
                                }
                            })
                            .build();
                    //注册完以后调用启动Server的方法
                    if (INSTANCE.isRunning()) {
                       Log.i(TAG,"服务启动成功");
                    } else {
                        INSTANCE.startup();
                    }
                    System.out.println("服务是否启动成功"+INSTANCE.isRunning());
                }
            }
        }


    }

    public void stop(){
        if (INSTANCE.isRunning()) {
            INSTANCE.shutdown();
        } else {
            Log.w("AndServer", "The server has not started yet.");
        }
    }
}
